package kortsoft.culcon.manager;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import kortsoft.culcon.model.Game;
import kortsoft.culcon.model.HibernateUtil;
import kortsoft.culcon.model.Player;

public class GameManager extends Manager {

	@SuppressWarnings("unchecked")
	public List<Game> listGames() {
		return getSession().createQuery("from Game").list();
	}

	public Game createGame(Game newGame) {
		Session session = getSession();
		HibernateUtil.getInstance().startTransaction();
		Integer gameCode = (Integer) session.save(newGame);		
		HibernateUtil.getInstance().endTransaction();
		Game savedGame = (Game) session.get(Game.class,gameCode);
		return savedGame;					
	}

	public Player addPlayer(Game game, Player newPlayer) {
		Session session = getSession();
		HibernateUtil.getInstance().startTransaction();
		newPlayer.setGame(game);
		session.save(newPlayer);
		game.addPlayer(newPlayer);
		session.update(game);				
		HibernateUtil.getInstance().endTransaction();
		Player player = (Player) session.get(Player.class,newPlayer.getPlayerCode());
		return player;		
	}

	@SuppressWarnings("unchecked")
	public Game getGameByName(String gameName) {
		Query query = getSession().createQuery("from Game where name = ?");
		query.setString(0,gameName);
		List<Game> games = query.list();		
		return games.get(0);
	}
}
